import Vue from 'vue'
import App from './App.vue'

// 引入 mavon-editor
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
// 引入echarts
import * as echarts from 'echarts';

// 引用饿了么
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
// 引入图标
import 'font-awesome/css/font-awesome.css'
// 引用router
import router from "./router";
// 引入目录
import store from "./store";
// 引用封装的api
import {getRequest} from "./utils/api";
import {postRequest} from "./utils/api";
import {putRequest} from "./utils/api";
import {deleteRequest} from "./utils/api";
import {downloadRequest} from "./utils/download";

import {initMenu} from "./utils/menus";

Vue.config.productionTip = false
// 安装element-ui
Vue.use(ElementUI);
Vue.use(mavonEditor);

Vue.prototype.$echarts = echarts

// 全局设置请求
Vue.prototype.getRequest = getRequest;
Vue.prototype.postRequest = postRequest;
Vue.prototype.putRequest = putRequest;
Vue.prototype.deleteRequest = deleteRequest;
Vue.prototype.downloadRequest = downloadRequest;


router.beforeEach((to,from,next) => {
  // console.log(to);
  // console.log(from);

   if(window.sessionStorage.getItem('tokenStr')){
    initMenu(router,store);
    if(!window.sessionStorage.getItem('user')){
      // 判断用户信息是否存在
      return getRequest('/admin/info').then(resp => {
        if(resp){
          // 存入用户信息
          window.sessionStorage.setItem('user',JSON.stringify(resp));
          store.commit('initUser',resp);
          next();
        }
      })
    }
    next(); // 需要next才能实现跳转,不然只有to,from
  }
   else if(to.path.startsWith('/common')&&to.path!='/common/CommonBlogEdit'){ // 开放Todo,blog
     next();
   }else{
    if(to.path == '/'){
      next();
    }else{
      next('/?redirect='+to.path);
    }
  }

})

new Vue({
  store,
  render: h => h(App),
  router,
  mode: 'history',
  base: process.env.BASE_URL,
}).$mount('#app')

import VueRouter from "vue-router";

Vue.use(VueRouter);

// 解决报错
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
// push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  // console.log(onReject + onResolve)
  // if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => {
    console.log(err)
    originalPush.call(this, location, onResolve, onReject)
  });
}
// replace
VueRouter.prototype.replace = function push (location, onResolve, onReject) {
  // console.log(onReject + onResolve)
  // if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => {
    console.log(err)
    originalPush.call(this, location, onResolve, onReject)
  })
}
